package de.ama.view;

import de.ama.crawler.Entry;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ama
 * Date: 15.02.11
 * Time: 10:47
 * To change this template use File | Settings | File Templates.
 */
public class EntryTableView extends JScrollPane {
    private JTable table = new JTable();
    private ClickHandler ch;
    private Entry selected = null;


    public EntryTableView() {
        table.setDefaultRenderer(Entry.class, new EntryCellREnderer());
        table.setRowHeight(180);
        table.setTableHeader(null);
        table.setBorder(null);
        table.setCellSelectionEnabled(true);
        setBackColor(Color.DARK_GRAY);


        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                selected = null;
                int selectedColumn = table.getSelectedColumn();
                int selectedRow = table.getSelectedRow();
                if(selectedColumn>=0 && selectedRow >=0){
                   selected = (Entry) table.getValueAt(selectedRow,selectedColumn);
                }

                if (ch != null && selected!=null) {
                    ch.onClick(selected, e);
                }
            }

        });

        setViewportView(table);

        this.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                getModel().setColumns(getWidth() / 100);
            }
        });
    }

    public void setBackColor(Color color) {
        setBackground(color);
        table.setGridColor(color);
        table.setBackground(color);
        getViewport().setBackground(color);
    }

    public Entry getSelected() {
        return selected;
    }

    public void setModel(EntryTableModel tm) {
        table.setModel(tm);
        table.invalidate();
    }

    public EntryTableModel getModel() {
        return (EntryTableModel) table.getModel();
    }

    public void setClickHandler(ClickHandler ch) {
        this.ch = ch;
    }

    public JTable getTable() {
        return table;
    }
}
